package http_resty

import (
	"context"
	"errors"
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/gogf/gf/util/gconv"
	"net/http"
	"time"
)

const (
	httpUrl = "http://127.0.0.1:9099/index"
)

func NewRestyHttpClient() *resty.Client {
	client := resty.New()
	client.SetTimeout(time.Second * 5) // 可以设置超时时间
	return client
}

func HttpGet(ctx context.Context, httpCli *resty.Client, name string) error {

	resp, errResp := httpCli.R().
		SetQueryParams(map[string]string{
			"name": name,
		}).
		SetContext(ctx).
		Get(httpUrl)

	if errResp != nil {
		return errors.New(fmt.Sprintf("%v 请求httpGet接口失败了! err: %v", name, errResp))
	}

	if resp.StatusCode() != http.StatusOK {
		return errors.New(fmt.Sprintf("%v 请求httpGet接口返回了错误码: %v", name, resp.StatusCode()))
	}

	// Notice 模拟处理延迟...
	time.Sleep(time.Second)

	fmt.Printf("name %v GET请求成功了! resp: %v \n", name, gconv.String(resp.Body()))

	return nil
}

type HttpRequestMeta struct {
	Name string `json:"name"`
}

func HttpPost(ctx context.Context, httpCli *resty.Client, name string) error {

	meta := HttpRequestMeta{
		Name: name,
	}

	resp, errResp := httpCli.R().
		SetContext(ctx).
		SetHeader("Content-Type", "application/json;charset=utf-8").
		SetBody(meta).
		Post(httpUrl)

	if errResp != nil {
		return errors.New(fmt.Sprintf("%v 请求httpPost接口失败了! err: %v", name, errResp))
	}

	if resp.StatusCode() != http.StatusOK {
		return errors.New(fmt.Sprintf("%v 请求httpPost接口返回了错误码: %v", name, resp.StatusCode()))
	}

	// Notice 模拟处理延迟...
	time.Sleep(time.Second * 2)

	fmt.Printf("name %v POST请求成功了! resp: %v \n", name, gconv.String(resp.Body()))

	return nil
}
